/* Service Request Task
This code will create an on load form task that will load the decision engine extension and make the required changes to the forms.

If you already have a SR custom task or other form code you can simply add the function all into your existing on load function.
*/
app.custom.formTasks.add('ServiceRequest', null, function(formObj, viewModel){  	
	formObj.boundReady( function () {

		addSelectBoxToDecision();
		
	});
}); 

/*START Decision Engine Extensions 

This code should be placed into your custom.js file, usually at the bottom. This is the function that will be called by the
on load function call above.

*/
function addSelectBoxToDecision() {
    //Will be needed to generate a dynamic enum list in the future
    var decisionActivityEnumGuid = '3a092d08-3327-4445-5579-ee714430df2f';

    var workItem = pageForm.viewModel;

    //Sets up the data for the select list, this will be dynamic in the future
    data = [
        {
            text: "Decision Needed",
            value: '6b1e17dc-0b86-828b-1be2-f1737bc65cf0'
        },
        {
            text: "Yes",
            value: '39851d47-994d-7eb4-313d-c3d5ae4cca3b'
        },
        {
            text: "No",
            value: '31f2c7f3-136f-5022-0ffa-d197a282b5d6'
        }
    ];

    //Walks the activities and adds the drop down if needed
    if (workItem.Activity.length > 0) {
        var decisionActivites = [];

        _.delay(function () {
            //DEBUG
            console.log('Activites Found: ' + workItem.Activity.length)

            $.merge( decisionActivites, WalkActivityTree(workItem.Activity, 'find'));
            
            for (var i = 0; i < decisionActivites.length; i++) {
                //DEBUG
                console.log('Adding event handler to: ' + decisionActivites[i]);
                //Adds an event handler for the change of the new select list and sets the decision activity
                $('#decision-selector[data-activity-id="' + decisionActivites[i] +'"]').change(function () {
                    var decision = $('#decision-selector option:selected').val();

                    //DEBUG
                    console.log('New Decision GUID: ' + decision);
                    console.log(this);
                    var id = this.dataset.activityId;
                    console.log('Activity Id: ' + id);

                    WalkActivityTree(workItem.Activity, 'update', id, decision);
                });
            }

        }, 1000);
    }
    
    //This function takes in an array of name/value pair objects and creates a select list
    function AddSelectBox(data, id, selected, activity) {
        var div = $('<div></div>');
        var title = $('<div class="editor-label">Decision</div>')
        var dropdown = $('<div class="editor-field" />');
        var list = $('<select id="decision-selector" class="k-dropdown-wrap" data-activity-id="' + id + '" />');

        //Find the particular form that we are working with, currently this is static
        var searchString = 'div[data-activity-id="' + id + '"]';
        var activityForm = $(searchString).parent().find('.activity-item-form');

        ////DEBUG - Did we find the activity form?
        //console.log('Search string: ' + searchString)
        //console.log('Activity Form:');
        //console.log(activityForm);

        var insertLocation = (activityForm.children())[0]; //Sets insert location after 'Title'

        for (var item in data) {
            //Checks to see if a selection was passed into the function
            if (selected && selected == data[item].value) {
                $('<option />', { value: data[item].value, text: data[item].text }).attr('selected','selected').appendTo(list);
            }
            else {
                $('<option />', { value: data[item].value, text: data[item].text }).appendTo(list);
            }
        }

        list.appendTo(dropdown);
        title.appendTo(div);
        dropdown.appendTo(div);
        div.appendTo(insertLocation);

        ////DEBUG - Does the new selectbox exist for the event handler add?
        //console.log($('#decision-selector'));
    }

    //Walks through activity tree and accepts two parameters, parent WI, and type of search (find, update)
    function WalkActivityTree(parent, type, id, decision) {
        var maArray = [];

        for (var i = 0; i < parent.length; i++) {
            var activity = parent[i];
            var activities = activity.Activity;
            var className = activity.ClassName;
            var children = activities.length;
            var isDecision = false;
            if(activity.ActivityDecision && activity.ActivityDecision.Id) isDecision = true;

            if (activities && children > 0) {

                //DEBUG
                console.log('Child Activites Found: ' + children);
                $.merge(maArray, WalkActivityTree(activities, type, id, decision) );
            }
            else if (
                className == "System.WorkItem.Activity.ManualActivity"
                && type == 'find'
                && isDecision == true
            ){
                if (activity.ActivityDecision) {
                    //DEBUG
                    console.log("Decision: " + activity.ActivityDecision.Name);

                    //Adds the select box to the decision activity
                    AddSelectBox(data, activity.Id, activity.ActivityDecision.Id, activity);
                    maArray.push(activity.Id);
                }
            }
            else if (
                className == "System.WorkItem.Activity.ManualActivity"
                && type == 'update'
                && activity.Id == id
            ){
                activity.ActivityDecision.Id = decision;
            }
        }

        return maArray;
    }
}